import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useLanguageStore } from './language'
import { useInfoDialogStore } from './infoDialog'
import { appox } from '@/appox/appox'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'

// 连接栏类型枚举
export const ConnectionBarType = {
  Connection: 1,
  Bus: 2,
  Video: 3,
  Audio: 4,
  Signal: 5,
  Sample: 6,
  PointCloud: 7,
  Function: 8
}

// 连接模式枚举
export const ConnectionMode = {
  Worker: 'worker',
  Bridge: 'bridge'
}

export const useConnectionStore = defineStore('connection', () => {
  const languageStore = useLanguageStore()
  const infoDialogStore = useInfoDialogStore()
  
  // 从URL参数获取连接模式
  const getConnectionModeFromUrl = () => {
    const urlParams = new URLSearchParams(window.location.search)
    const mode = urlParams.get('mode')
    return mode === 'bridge' ? ConnectionMode.Bridge : ConnectionMode.Worker
  }
  
  // 状态
  const isConnected = ref(false)
  const connectionMode = ref(getConnectionModeFromUrl())
  
  // Worker模式配置
  const serverIp = ref(localStorage.getItem('AppoxJsTest.ConnectionIp') || '127.0.0.1')
  const serverPort = ref(localStorage.getItem('AppoxJsTest.ConnectionPort') || '12344')
  
  // Bridge模式配置
  const bridgeIp = ref(localStorage.getItem('AppoxJsTest.ConnectionBridgeIp') || '127.0.0.1')
  const bridgeUserPort = ref(localStorage.getItem('AppoxJsTest.ConnectionBridgeUserPort') || '22344')
  const bridgeConsolePort = ref(localStorage.getItem('AppoxJsTest.ConnectionBridgeConsolePort') || '33345')

  // 连接状态
  const connectionStatus = ref('default')
  const busStatus = ref('default')
  const videoStatus = ref('default')
  const audioStatus = ref('default')
  const signalStatus = ref('default')
  const sampleStatus = ref('default')
  const pointCloudStatus = ref('default')
  const functionStatus = ref('default')

  // 工具提示文本
  const connectionTooltip = ref(languageStore.isChinese ? '未连接' : 'Disconnected')
  const busTooltip = ref(languageStore.isChinese ? '总线数据: (无)' : 'Bus data: (None)')
  const videoTooltip = ref(languageStore.isChinese ? '视频数据: (无)' : 'Video data: (None)')
  const audioTooltip = ref(languageStore.isChinese ? '音频数据: (无)' : 'Audio data: (None)')
  const signalTooltip = ref(languageStore.isChinese ? '信号数据: (无)' : 'Signal data: (None)')
  const sampleTooltip = ref(languageStore.isChinese ? '样本数据: (无)' : 'Sample data: (None)')
  const pointCloudTooltip = ref(languageStore.isChinese ? '点云数据: (无)' : 'Point cloud: (None)')
  const functionTooltip = ref(languageStore.isChinese ? '函数数据: (无)' : 'Function data: (None)')

  // 计算属性
  const isWorkerMode = computed(() => connectionMode.value === ConnectionMode.Worker)
  const isBridgeMode = computed(() => connectionMode.value === ConnectionMode.Bridge)

  // 加载连接配置
  function loadConnectionConfig() {
    if (isWorkerMode.value) {
      const savedIp = localStorage.getItem('AppoxJsTest.ConnectionIp')
      const savedPort = localStorage.getItem('AppoxJsTest.ConnectionPort')
      if (savedIp) serverIp.value = savedIp
      if (savedPort) serverPort.value = savedPort
    } else {
      const savedBridgeIp = localStorage.getItem('AppoxJsTest.ConnectionBridgeIp')
      const savedUserPort = localStorage.getItem('AppoxJsTest.ConnectionBridgeUserPort')
      const savedConsolePort = localStorage.getItem('AppoxJsTest.ConnectionBridgeConsolePort')
      if (savedBridgeIp) bridgeIp.value = savedBridgeIp
      if (savedUserPort) bridgeUserPort.value = savedUserPort
      if (savedConsolePort) bridgeConsolePort.value = savedConsolePort
    }
  }

  // 保存连接配置
  function saveConnectionConfig() {
    if (isWorkerMode.value) {
      if (serverIp.value) localStorage.setItem('AppoxJsTest.ConnectionIp', serverIp.value)
      if (serverPort.value) localStorage.setItem('AppoxJsTest.ConnectionPort', serverPort.value)
    } else {
      if (bridgeIp.value) localStorage.setItem('AppoxJsTest.ConnectionBridgeIp', bridgeIp.value)
      if (bridgeUserPort.value) localStorage.setItem('AppoxJsTest.ConnectionBridgeUserPort', bridgeUserPort.value)
      if (bridgeConsolePort.value) localStorage.setItem('AppoxJsTest.ConnectionBridgeConsolePort', bridgeConsolePort.value)
    }
  }

  // 动作
  async function connect() {
    if (isConnected.value) {
      appox.reconnect();
      return
    }
    
    try {
      if (isWorkerMode.value) {
        if (!serverIp.value || !serverPort.value) {
          throw new Error('Empty IP or empty port')
        }
        await appox.initializeWorkerConnection(serverIp.value, serverPort.value)
      } else {
        if (!bridgeIp.value || !bridgeUserPort.value || !bridgeConsolePort.value) {
          throw new Error('Empty IP or empty ports')
        }
        await appox.initializeBridgeConnection(bridgeIp.value, bridgeUserPort.value, bridgeConsolePort.value)
      }
      
      isConnected.value = true
      saveConnectionConfig()
    } catch (error) {
      console.error('Connect error:', error)
    }
  }

  async function disconnect() {
    if (!isConnected.value) return
    
    try {
      await appox.disconnect()
      isConnected.value = false
      resetConnectionBars()
    } catch (error) {
      console.error('Disconnect error:', error)
    }
  }

  function updateConnectionBar(type, buttonType, tooltipText) {
    switch (type) {
      case ConnectionBarType.Connection:
        connectionStatus.value = buttonType
        connectionTooltip.value = tooltipText
        break
      case ConnectionBarType.Bus:
        busStatus.value = buttonType
        busTooltip.value = tooltipText
        break
      case ConnectionBarType.Video:
        videoStatus.value = buttonType
        videoTooltip.value = tooltipText
        break
      case ConnectionBarType.Audio:
        audioStatus.value = buttonType
        audioTooltip.value = tooltipText
        break
      case ConnectionBarType.Signal:
        signalStatus.value = buttonType
        signalTooltip.value = tooltipText
        break
      case ConnectionBarType.Sample:
        sampleStatus.value = buttonType
        sampleTooltip.value = tooltipText
        break
      case ConnectionBarType.PointCloud:
        pointCloudStatus.value = buttonType
        pointCloudTooltip.value = tooltipText
        break
      case ConnectionBarType.Function:
        functionStatus.value = buttonType
        functionTooltip.value = tooltipText
        break
      default:
        return
    }
  }

  function resetConnectionBars() {
    updateConnectionBar(ConnectionBarType.Connection, 'default', languageStore.isChinese ? '未连接' : 'Disconnected')
    updateConnectionBar(ConnectionBarType.Bus, 'default', languageStore.isChinese ? '总线数据: (无)' : 'Bus data: (None)')
    updateConnectionBar(ConnectionBarType.Video, 'default', languageStore.isChinese ? '视频数据: (无)' : 'Video data: (None)')
    updateConnectionBar(ConnectionBarType.Audio, 'default', languageStore.isChinese ? '音频数据: (无)' : 'Audio data: (None)')
    updateConnectionBar(ConnectionBarType.Signal, 'default', languageStore.isChinese ? '信号数据: (无)' : 'Signal data: (None)')
    updateConnectionBar(ConnectionBarType.Sample, 'default', languageStore.isChinese ? '样本数据: (无)' : 'Sample data: (None)')
    updateConnectionBar(ConnectionBarType.PointCloud, 'default', languageStore.isChinese ? '点云数据: (无)' : 'Point cloud: (None)')
    updateConnectionBar(ConnectionBarType.Function, 'default', languageStore.isChinese ? '函数数据: (无)' : 'Function data: (None)')
  }

  // 更新传输状态栏
  function updateTransferStatistics(stat) {
    const updateBar = (type, title, barType) => {
      const data = stat[type]
      if (!data || (data.successBytesPerSecond + data.failBytesPerSecond) === 0n) {
        updateConnectionBar(barType, 'default', languageStore.isChinese ? `${title}(无)` : `${title}(None)`)
        return
      }

      const successKbps = Math.max(data.successBytesPerSecond > 0n ? 0.1 : 0, Number(data.successBytesPerSecond * 8n / 1024n))
      const totalBytesPerSecond = data.successBytesPerSecond + data.failBytesPerSecond
      const totalKbps = Math.max(totalBytesPerSecond > 0n ? 0.1 : 0, Number(totalBytesPerSecond * 8n / 1024n))
      const tooltipText = `${title}${successKbps.toFixed(1)} / ${totalKbps.toFixed(1)} kbps`

      // 如果有失败的数据，显示警告色，否则显示成功色
      const buttonType = data.failBytesPerSecond > 0n ? 'warning' : 'success'
      updateConnectionBar(barType, buttonType, tooltipText)
    }

    updateBar(appoxEnums.TransferStreamType.BusMessage, languageStore.isChinese ? '总线数据: ' : 'Bus data: ', ConnectionBarType.Bus)
    updateBar(appoxEnums.TransferStreamType.VideoFrame, languageStore.isChinese ? '视频数据: ' : 'Video data: ', ConnectionBarType.Video)
    updateBar(appoxEnums.TransferStreamType.AudioFrame, languageStore.isChinese ? '音频数据: ' : 'Audio data: ', ConnectionBarType.Audio)
    updateBar(appoxEnums.TransferStreamType.Signal, languageStore.isChinese ? '信号数据: ' : 'Signal data: ', ConnectionBarType.Signal)
    updateBar(appoxEnums.TransferStreamType.GeneralSample, languageStore.isChinese ? '样本数据: ' : 'Sample data: ', ConnectionBarType.Sample)
    updateBar(appoxEnums.TransferStreamType.PointCloud, languageStore.isChinese ? '点云数据: ' : 'Point cloud: ', ConnectionBarType.PointCloud)
    updateBar(appoxEnums.TransferStreamType.Function, languageStore.isChinese ? '函数数据: ' : 'Function data: ', ConnectionBarType.Function)
  }

  // 处理F按钮点击事件
  async function handleFunctionButtonClick() {
    try {
      // 检查应用状态是否为运行中
      const appStatus = await agencyAsync.getAppStatus()
      if (appStatus !== appoxEnums.ApplicationStatus.Running) {
        return
      }

      // 获取功能数据统计信息
      const statXmlString = await agencyAsync.getGlobalVariable("System.FunctionDataStat", null)
      if (!statXmlString) {
        return
      }

      // 解析XML数据
      const parser = new DOMParser()
      const statXml = parser.parseFromString(statXmlString, "text/xml")
      
      const total = parseInt(statXml.documentElement.getAttribute("total") || "0")
      
      const items = []
      const sNodes = statXml.documentElement.getElementsByTagName("s")
      for (let i = 0; i < sNodes.length; i++) {
        const sNode = sNodes[i]
        const id = sNode.getAttribute("id")
        const value = parseInt(sNode.textContent || "0")
        const k = parseFloat(sNode.getAttribute("k") || "0")
        items.push({ id, value, k })
      }
      
      // 按数据量降序排序
      items.sort((a, b) => b.value - a.value)

      // 生成显示行
      const rows = []
      for (const item of items) {
        const percentage = total > 0 ? ((item.value / total) * 100).toFixed(1) : "0.0"
        rows.push(`${item.id}: ${percentage}% (${item.value} byte/s, ${item.k.toFixed(1)} pkt/s)`)
      }

      // 显示InfoDialog
      const title = languageStore.isChinese ? '功能数据量统计' : 'Function Data Volume Stat'
      const message = rows.length > 0 ? rows.join('\n') : (languageStore.isChinese ? '无数据' : 'No data')
      await infoDialogStore.show(title, message)
    } catch (error) {
      console.error('Failed to get function data statistics:', error)
    }
  }

  return {
    // 状态
    isConnected,
    connectionMode,
    serverIp,
    serverPort,
    bridgeIp,
    bridgeUserPort,
    bridgeConsolePort,
    connectionStatus,
    busStatus,
    videoStatus,
    audioStatus,
    signalStatus,
    sampleStatus,
    pointCloudStatus,
    functionStatus,
    // 工具提示
    connectionTooltip,
    busTooltip,
    videoTooltip,
    audioTooltip,
    signalTooltip,
    sampleTooltip,
    pointCloudTooltip,
    functionTooltip,
    // 计算属性
    isWorkerMode,
    isBridgeMode,
    // 动作
    loadConnectionConfig,
    saveConnectionConfig,
    connect,
    disconnect,
    updateConnectionBar,
    resetConnectionBars,
    updateTransferStatistics,
    handleFunctionButtonClick
  }
}) 